package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    /**
     * thymeleaf 页面跳转 以及渲染
     * @param searchMap
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap, Model model){
        //进行 请求参数的处理
        handlerSearchMap(searchMap);

        //进行 数据的查询
        Map searchResult = searchService.search(searchMap);
        model.addAttribute("resultMap",searchResult);
        model.addAttribute("searchMap",searchMap);

        //封装分页数据并返回
        //总记录数
        //当前页
        //每页显示多少条
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(String.valueOf(searchResult.get("total"))),
                Integer.parseInt(String.valueOf(searchResult.get("pageNum"))),
                Page.pageSize
        );
        model.addAttribute("page",page);

        //动态的进行路径的拼接 url 拼接
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0){
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if (!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }
            //去掉 最后 末尾 的 &
            String urlString = url.substring(0, url.length() - 1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }



        return "search";
    }

    /**
     * 全文检索
     * @param searchMap
     * @return
     */
    @GetMapping
    @ResponseBody
    public Result search(@RequestParam Map<String,String> searchMap){
        //特殊符号处理
        handlerSearchMap(searchMap);
        Map search = searchService.search(searchMap);
        return new Result(true, StatusCode.OK,"查询成功",search);
    }

    //对搜索入参带有特殊符号进行处理
    private void handlerSearchMap(Map<String, String> searchMap) {
        if (searchMap == null){
            throw new RuntimeException("传入参数为空！！");
        }
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec_")){
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }
}
